const axios = require('axios')
const cheerio = require('cheerio')
const dateformat = require('dateformat')

const db = require('./db')

// 入口
const entry = 'http://wlkt.yn.gov.cn/onlinelearn/getResourceAdvList.action?argumentxId=1'

// 获取列表页数据
function get(page = 2) {
  // 重新分页
  axios.get(entry, { params: { page } }).then((res) => {
    format(res.data)
  }).catch((err) => {
    console.warn('资源处理失败:', err.toString())
  })
}

function format(content) {
  content = cheerio.load(content)('.center .area a').has('img')
  content.each((i, e) => {
    const item = cheerio.load(e)
    const data = {
      title: item('img').attr('alt'),
      time: dateformat('yyyy-mm-dd'),
      type: 'video',
      info: item('img').attr('src'),
      url: item('a').attr('href'),
    }
    stash(data)
  })
}

async function stash(data = {}) {
  if (await db.isExists(data)) {
    console.log(data.title, 'is exists')
  } else {
    db.save(data).then(_ => console.log(data.title, ' Save Success')).catch((err) => {
      console.warn('Save Error ', err.toString())
    })
  }
}

let i = 1

function init() {
  if (i !== 48) {
    get(i)
    i += 1
    setTimeout(() => {
      init()
    }, 1000)
  }
}
init()